<?php
declare (strict_types=1);

namespace app\api\controller\chat;

use think\facade\Db;
use think\worker\Server;
use Workerman\Lib\Timer;

define('HEARTBEAT_TIME', 20);// 心跳间隔55秒

class ChatController extends Server
{
    protected $socket = 'websocket://0.0.0.0:2345';

    /*public function __construct()
    {
        parent::__construct();
    }*/

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        // Validate incoming data
        $arr = json_decode($data);

        if ($arr === null) {
            // Handle JSON decoding error
            echo 'Invalid JSON data';
            return;
        }

        // Bind connection if uid is not set
        if (!isset($connection->uid)) {
            $connection->uid                                = $arr->uid;
            $this->worker->uidConnections[$connection->uid] = $connection;
        }

        // Check if recipient is online and send the message
        if (isset($this->worker->uidConnections[$arr->to_user_id])) {
            $recipientConnection = $this->worker->uidConnections[$arr->to_user_id];
            $recipientConnection->send($data);
        } else {
            echo 'User ' . $arr->to_user_id . ' is offline.';
        }
    }

}

